package cc.rengu.oltp.utility.util;

import java.io.ByteArrayOutputStream;

/**
 * 字符串与十六进制转换工具类
 * Created by 王成 on 2017/11/25.
 */
public class HexUtil {

    private static final String HEX_STRING = "0123456789ABCDEF";

    /**
     * 将字符串转换成十六进制的字符串
     *
     * @param src ASCII码字符串
     * @return 十六进制字符串
     */
    public static String StringtoHex(String src) throws Exception {
        /* 根据默认编码获取字节数组 */
        byte[] bytes = src.getBytes("UTF-8");
        StringBuilder dest = new StringBuilder(bytes.length * 2);
        /* 将字节数组中每个字节拆解成2位16进制整数 */
        for (int i = 0; i < bytes.length; i++) {
            dest.append(HEX_STRING.charAt((bytes[i] & 0xf0) >> 4));
            dest.append(HEX_STRING.charAt((bytes[i] & 0x0f) >> 0));
        }
        return dest.toString().toUpperCase();
    }

    /**
     * 将16进制字符串转换ASCII字符串
     *
     * @param src 十六进制字符串
     * @return ASCII码字符串
     */
    public static String HextoString(String src) throws Exception {
        src = src.toUpperCase();
        ByteArrayOutputStream baos = new ByteArrayOutputStream(src.length() / 2);
        /* 将每2位16进制整数组装成一个字节 */
        for (int i = 0; i < src.length(); i += 2) {
            baos.write((HEX_STRING.indexOf(src.charAt(i)) << 4 | HEX_STRING.indexOf(src.charAt(i + 1))));
        }
        return new String(baos.toByteArray(), "UTF-8");
    }
}
